package cn.xuchunh.okhttpdemo.toolbox;

import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;

import cn.xuchunh.okhttpdemo.ResponseDelivery;

/**
 * Created by Administrator on 2015/12/28.
 */
public class MyRequest {

    private ResponseListener listener;
    private Call call;
    private ResponseDelivery delivery;

    public MyRequest(Call call, ResponseDelivery delivery) {
        this(call, delivery, null);
    }

    public MyRequest(Call call, ResponseDelivery delivery, ResponseListener listener) {
        this.call = call;
        this.delivery = delivery;
        this.listener = listener;
    }

    public void run() {
        if (call != null) {
            call.enqueue(new MyCallback());
        }
    }

    private class MyCallback implements Callback {
        @Override
        public void onFailure(final Request request, final IOException e) {
            if (delivery != null && listener != null) {
                delivery.deliverResponse(new Runnable() {
                    @Override
                    public void run() {
                        listener.onFailure(request, e);
                    }
                });
            }
        }

        @Override
        public void onResponse(final Response response) throws IOException {
            if (delivery != null && listener != null) {
                delivery.deliverResponse(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            listener.onResponse(response);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        }
    }

    public interface ResponseListener {
        void onResponse(Response response) throws IOException;

        void onFailure(Request request, IOException e);
    }

}
